package com.deekian.tools.bluetoothtrigger.receiver;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.deekian.tools.bluetoothtrigger.utils.SharedPreferencesTools;
import com.deekian.tools.bluetoothtrigger.utils.WifiTools;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class BluetoothBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        JSONArray cacheDeviceArray = SharedPreferencesTools.getCacheBluetoothDeviceArray(context);
        List<String> cacheDeviceAddress = new ArrayList<>();
        for (int i = 0; i < cacheDeviceArray.length(); i++) {
            try {
                cacheDeviceAddress.add(cacheDeviceArray.getJSONObject(i).getString(SharedPreferencesTools.BLUETOOTH_DEVICE_ADDRESS_KEY));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        switch (intent.getAction()) {
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                if (SharedPreferencesTools.testBluetoothBroadcastReceiver(context) &&
                        cacheDeviceAddress.contains(device.getAddress()) &&
                        !WifiTools.myWifiHotspotIsOpen(context)) {
                    WifiTools.openMyWifiHotspot(context);
                }
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                if (SharedPreferencesTools.testBluetoothBroadcastReceiver(context) &&
                        cacheDeviceAddress.contains(device.getAddress()) &&
                        WifiTools.myWifiHotspotIsOpen(context)) {
                    WifiTools.cloneWifiHotspot(context);
                }
                break;
            //上面的两个链接监听，其实也可以BluetoothAdapter实现，修改状态码即可
            default:
                System.out.println("---->   接收到的Intent的Action为：" + intent.getAction() + "\n 消息内容是：" + intent.getStringExtra("msg"));
                System.out.println(SharedPreferencesTools.getCacheBluetoothDeviceArray(context.getApplicationContext()));
                break;
        }

    }


}
